package com.mall.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mall.common.Const;
import com.mall.common.ServerResponse;
import com.mall.dao.MmallCartMapper;
import com.mall.dao.MmallOrderItemMapper;
import com.mall.dao.MmallOrderMapper;
import com.mall.dao.MmallPayInfoMapper;
import com.mall.dao.MmallProductMapper;
import com.mall.dao.MmallShippingMapper;
import com.mall.pojo.MmallCart;
import com.mall.pojo.MmallOrder;
import com.mall.pojo.MmallOrderExample;
import com.mall.pojo.MmallOrderExample.Criteria;
import com.mall.pojo.MmallOrderItem;
import com.mall.pojo.MmallPayInfo;
import com.mall.pojo.MmallProductWithBLOBs;
import com.mall.pojo.MmallShipping;
import com.mall.service.IOrderService;
import com.mall.util.BigDecimalUtil;
import com.mall.util.DatetimeUtil;
import com.mall.util.FTPUtil;
import com.mall.util.PropertiesUtil;
import com.mall.vo.OrderItemVo;
import com.mall.vo.OrderProductVo;
import com.mall.vo.OrderVo;
import com.mall.vo.ShippingVo;

@Service
public class OrderServiceImpl implements IOrderService {
	
	@Autowired
	private MmallOrderMapper orderMapper;
	
	@Autowired
	private MmallOrderItemMapper orderItemMapper;
	
	@Autowired
	private MmallPayInfoMapper payInfoMapper;
	
	@Autowired
	private MmallCartMapper cartMapper;
	
	@Autowired
	private MmallProductMapper productMapper;
	
	@Autowired
	private MmallShippingMapper shippingMapper;
	
	Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
	
	@Override
	public ServerResponse pay(Integer userId, long orderNo, String path){
		
		Map<String,String> map = new HashMap<String,String>();
		
		//根据订单号和用户id查询订单是否存在
		MmallOrder order = orderMapper.selectByUserIdOrderNo(userId,orderNo);
		if(order == null){
			return ServerResponse.createByErrorMessage("用户没有该订单");
		}
		
		map.put("orderNo",String.valueOf(order.getOrderNo()));
		
		
		/* 接下来是支付宝代码 ,复制粘贴并修改. */
		
		 // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = String.valueOf(order.getOrderNo());

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = new StringBuffer().append("请扫码支付,订单号为:").append(order.getOrderNo()).toString();

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = order.getPayment().toString();

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";
        
        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        String body = new StringBuffer().append("订单号").append(order.getOrderNo()).append(" 购买商品共").append(order.getPayment()).append("元").toString();

        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");

        // 支付超时，定义为120分钟
        String timeoutExpress = "120m";

        
        
        // 商品明细列表，需填写购买商品详细信息，
        
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        
        //通过用户id和订单id查询订单中所有的商品,并添加到list集合中.
        List<MmallOrderItem> orderItem = orderItemMapper.selectByUserIdOrderNo(userId,orderNo);
        for (MmallOrderItem item : orderItem) { 
        	
        	// 创建一个商品信息，参数含义分别为商品id、名称、单价（单位为分）、数量，
        	GoodsDetail good = GoodsDetail.newInstance(item.getProductId().toString(), 
        									item.getProductName().toString(),
        									BigDecimalUtil.mult(item.getCurrentUnitPrice().doubleValue(), new Double(100).doubleValue()).longValue(),
        									item.getQuantity());
        	
        	goodsDetailList.add(good);
        }
        
        // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        // GoodsDetail goods = GoodsDetail.newInstance("goods_id001", "xxx小面包", 1000, 1);
        // 创建好一个商品后添加至商品明细列表
        // goodsDetailList.add(goods1);

        
        /**************
         	设置回调地址 , 需要使用natapp, 进行内网穿透
        **************/
        
        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
            .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
            .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
            .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
            .setTimeoutExpress(timeoutExpress)
            .setNotifyUrl("http://eqyxhz.natappfree.cc/zhaut-mall/order/callback")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
            .setGoodsDetailList(goodsDetailList);
       
        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
        *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
        */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
        *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
        */
        AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
        
        
        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                logger.info("支付宝预下单成功: )");

                AlipayTradePrecreateResponse response = result.getResponse();
                dumpResponse(response);
                
             //** 重点 **//   
             
               //将生成的二维码上传到ftp服务器上,首先保存到tomcat目录下哦
                
                //首先判断tomcat的uplaod目录是否存在,不存在创建一个目录
                File file = new File(path);
                if(!file.exists()){
                	file.mkdirs();
                }
                
                //二维码路径 : ../upload/qr-212142141.png
                //注意细节!!!! 得到的path路径是不含有后面的/符号的.要手动加上!!!
                String qrPath = String.format(path + "/qr-%s.png", response.getOutTradeNo());
                System.out.println("qrPath: "+qrPath);
                
                //二维码图片名 :   qr-212142141.png
                String qrFileName = String.format("qr-%s.png", response.getOutTradeNo());
                
                //生成二维码
                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, qrPath);
                
                			//                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);
                // 
                File targetFile = new File(path,qrFileName);
                System.out.println("targetFile: "+targetFile);
                
                //上传到ftp服务器上.
				try {
					FTPUtil.uploadFile(Lists.newArrayList(targetFile));
					
				} catch (IOException e) {
					logger.error("上传二维码异常",e);
					e.printStackTrace();
				}
                
                logger.info("qrPath:" + qrPath);
                
                map.put("qrPath", PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFile.getName());
                System.out.println("---ftp.server.http.prefix"+targetFile.getName());
                return ServerResponse.createBySuccess(map);
                
            case FAILED:
            	logger.error("支付宝预下单失败!!!");
                return ServerResponse.createByErrorMessage("支付宝预下单失败!!!");

            case UNKNOWN:
            	logger.error("系统异常，预下单状态未知!!!");
                return ServerResponse.createByErrorMessage("系统异常，预下单状态未知!!!");

            default:
            	logger.error("不支持的交易状态，交易返回异常!!!");
                return ServerResponse.createByErrorMessage("不支持的交易状态，交易返回异常!!!");
		
        }
        
	}
	
	  // 简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            logger.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
            	logger.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                    response.getSubMsg()));
            }
            logger.info("body:" + response.getBody());
        }
    }
    
    @Override
    public ServerResponse aliCallback(Map<String ,String> params){
    	
    	//支付宝异步通知的参数文档:
    	//https://docs.open.alipay.com/194/103296/
    	
    	//订单号
    	Long orderNo = Long.parseLong(params.get("out_trade_no"));
    	
    	//支付宝交易号
    	String tradeNo = params.get("trade_no");
    	
    	//文档: https://docs.open.alipay.com/194/103296/
    	//交易目前所处的状态,
    	//共有四种状态:		(1)WAIT_BUYER_PAY(交易创建，等待买家付款)
    	//				    (2)TRADE_CLOSED(未付款交易超时关闭，或支付完成后全额退款)
    	//				    (3)TRADE_SUCCESS(交易支付成功)
    	//					(4)TRADE_FINISHED(交易结束，不可退款)
    	
    	String tradeStatus = params.get("trade_status");
    	
    	MmallOrder order = orderMapper.selectByOrderNo(orderNo);
    	if(order == null){
    		return ServerResponse.createByErrorMessage("非本商城的订单,回调忽略");
    	}
    	
    	if(order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()){
    		return ServerResponse.createBySuccess("支付宝重复调用");
    	}
    	
    	if(Const.AlipayCallback.TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)){
    		
    		//交易状态成功
    		
    		//gmt_payment : 交易付款时间
    		order.setPaymentTime(DatetimeUtil.strToDate(params.get("gmt_payment")));
    		
    		//交易成功的状态为:20
    		order.setStatus(Const.OrderStatusEnum.PAID.getCode());
    		
    		//更新订单状态
    		orderMapper.updateByPrimaryKeySelective(order);
    	}
    	
    	MmallPayInfo info = new MmallPayInfo();
    	info.setUserId(order.getUserId());
    	info.setOrderNo(orderNo);
    	// '支付平台:1-支付宝,2-微信',
    	info.setPayPlatform(1);
    	//支付宝支付流水号'
    	info.setPlatformNumber(tradeNo);
    	//'支付宝支付状态'
    	info.setPlatformStatus(tradeStatus);
    	
    	payInfoMapper.insert(info);
    	
		return ServerResponse.createBySuccess();
		
    }
    
    @Override
    public ServerResponse<Boolean> queryOrderPaySatus(Integer userId,Long orderNo){
    	
    	MmallOrder order = orderMapper.selectByUserIdOrderNo(userId, orderNo);
    	if(order == null){
    		return ServerResponse.createByErrorMessage("没有查到该订单");
    	}
    	
    	//只要状态大于20,(已付款,已发货,交易成功等)都认为是订单是成功的.
    	if(order.getStatus() >= 20){
    		return ServerResponse.createBySuccess();
    	}
    	return ServerResponse.createByError();
    }
    
    
    
	@Override			//创建订单
	public ServerResponse createOrder(Integer userId, Integer shippingId) {
		
		//假设只能从购物车中提交订单购买商品 ,先不考虑直接选中商品购买等其他情况.
		
		//查出购物车中该用户已勾选的商品
		List<MmallCart> cartList = cartMapper.selectCartCheckedByUserId(userId);
		
		ServerResponse response = this.getCartOrderItem(userId,cartList);
		
		//不成功
		if(!response.isSuccess()){
			return response;
		}
		
		//成功,得到订单中商品明细
		List<MmallOrderItem> orderItemList = (List<MmallOrderItem>) response.getData();
		
		
		//计算订单的总价
		BigDecimal totalPrice = new BigDecimal("0");
		for(MmallOrderItem item : orderItemList ){
			totalPrice = BigDecimalUtil.add(totalPrice.doubleValue(), item.getTotalPrice().doubleValue());
		}
		
		//生成订单,并将订单插入到数据库中.
		MmallOrder order = this.assembleOrder(userId,shippingId,totalPrice);
		if(order == null){
			return ServerResponse.createByErrorMessage("生成订单出错");
		}
		
		if(orderItemList.isEmpty()){
			return ServerResponse.createByErrorMessage("购物车为空");
		}
		
		//给每种商品设置订单号,同一购物车中的订单号肯定是一样的啊. 
		for(MmallOrderItem item :orderItemList ){
			item.setOrderNo(order.getOrderNo());
		} 
		
		//mybatis 批量插入  , 插入订单明细
		orderItemMapper.batchInsert(orderItemList);
		
		//生成订单成功,减少产品的库存
		this.reduceProductStock(orderItemList);
		
		
		//清空购物车中勾选中的商品,也就是付过款的商品.
		this.clearCart(cartList);
		
		   
		//返回给前端数据
		OrderVo orderVo = this.assembleOrderVo(order,orderItemList);
		
		return ServerResponse.createBySuccess(orderVo);
	}
	
	
	//组装返回给前端的数据
	private OrderVo assembleOrderVo(MmallOrder order,List<MmallOrderItem> orderItemList){
		
		OrderVo vo = new OrderVo();
		vo.setOrderNo(order.getOrderNo());
		vo.setPayment(order.getPayment());
		vo.setPaymentType(order.getPaymentType());
		vo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());
		
		vo.setPostage(order.getPostage());
		vo.setStatus(order.getStatus());
		vo.setStatusDesc(Const.OrderStatusEnum.valueOf(order.getStatus()).getDesc());
		
		vo.setPaymentTime(DatetimeUtil.dateToStr(order.getPaymentTime()));
		vo.setSendTime(DatetimeUtil.dateToStr(order.getSendTime()));
		vo.setEndTime(DatetimeUtil.dateToStr(order.getEndTime()));
		vo.setCloseTime(DatetimeUtil.dateToStr(order.getCloseTime()));
		vo.setCreateTime(DatetimeUtil.dateToStr(order.getCreateTime()));
		
		vo.setShippingId(order.getShippingId());
		
		//组装收货人的信息
		MmallShipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
		if(shipping != null){
			vo.setReceiverName(shipping.getReceiverName());
			vo.setShippingVo(assembleShippingVo(shipping));
		}
		
		vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
		
		//组装orderItemVoList 订单明细
		List<OrderItemVo> itemVo = Lists.newArrayList();
		
		for(MmallOrderItem orderItem : orderItemList ){
			OrderItemVo vos = assembleOrderItemVo(orderItem);
			itemVo.add(vos);
		}
		
		vo.setOrderItemVoList(itemVo);
		
		return vo;
	}
	
	//组装OrderItemVo 订单明细. 
	private OrderItemVo assembleOrderItemVo(MmallOrderItem orderItem){
		
		OrderItemVo vo = new OrderItemVo();
		
		vo.setOrderNo(orderItem.getOrderNo());
		vo.setProductId(orderItem.getProductId());
		vo.setProductName(orderItem.getProductName());
		vo.setProductImage(orderItem.getProductImage());
		vo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
		vo.setQuantity(orderItem.getQuantity());
		vo.setTotalPrice(orderItem.getTotalPrice());
		vo.setCreateTime(DatetimeUtil.dateToStr(orderItem.getCreateTime()));
		
		return vo;
	}
	
	//组装收货人的信息
	private ShippingVo assembleShippingVo(MmallShipping shipping){
		
		ShippingVo shippingVo = new ShippingVo();
		shippingVo.setReceiverAddress(shipping.getReceiverAddress());
		shippingVo.setReceiverCity(shipping.getReceiverAddress());
		shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
		shippingVo.setReceiverMobile(shipping.getReceiverMobile());
		shippingVo.setReceiverName(shipping.getReceiverName());
		shippingVo.setReceiverPhone(shipping.getReceiverPhone());
		shippingVo.setReceiverProvince(shipping.getReceiverProvince());
		shippingVo.setReceiverZip(shipping.getReceiverZip());
		
		return shippingVo;
	}
	
	//清空购物车中勾选中的商品,也就是已生成订单的商品.
	private void clearCart(List<MmallCart> cartList){
		
		for(MmallCart cart:cartList ){
			cartMapper.deleteByPrimaryKey(cart.getId());
		}
	}
	
	//减少产品的库存
	private void reduceProductStock(List<MmallOrderItem> orderItemList){
		
		for(MmallOrderItem item : orderItemList){
			
			MmallProductWithBLOBs product = productMapper.selectByPrimaryKey(item.getProductId());
			product.setStock(product.getStock()-item.getQuantity());
			productMapper.updateByPrimaryKeySelective(product);
		}
	}
	
	
	private MmallOrder assembleOrder(Integer userId,Integer shippingId ,BigDecimal totalPrice){
		
		MmallOrder order = new MmallOrder();
		
		//生成订单号 , 使用currentTime + 取余 后的结果
		order.setOrderNo(this.getOrderNo());
		//总金额
		order.setPayment(totalPrice);
		//'支付类型,1-在线支付',
		order.setPaymentType(1);
		//运费
		order.setPostage(0);
		//'订单状态:0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭',
		order.setStatus(10);
		
		order.setShippingId(shippingId);
		order.setUserId(userId);
		
		int count = orderMapper.insert(order);
		if(count > 0 ){
			return order;
		}
		return null;
	}
	
	//随机生成订单号
	private long getOrderNo(){
		
		long time = System.currentTimeMillis() ;
		return time + new Random().nextInt(100) ;
	}
	
	
	//组装订单中的商品明细.
	private ServerResponse getCartOrderItem(Integer userId,List<MmallCart> cartList ){
		
		if(cartList == null){
			return ServerResponse.createByErrorMessage("购物车为空");
		}
		
		//用来装各个商品的明细.
		List<MmallOrderItem> orderItemList = new ArrayList();
		
		//校验商品的数据,包括商品的状态和数量
		for (MmallCart cart : cartList) {
			
			MmallProductWithBLOBs product = productMapper.selectByPrimaryKey(cart.getProductId());
			
			//校验商品状态 -->  '商品状态.1-在售 2-下架 3-删除',
			if(product.getStatus() != 1){
				return ServerResponse.createByErrorMessage(product.getName()+"商品不是在售状态");
			}
			
			//校验数量,若超过库存则返回错误
			if( cart.getQuantity() >= product.getStock() ){
				return ServerResponse.createByErrorMessage("您勾选的"+product.getName()+"商品超过最大库存了");
			}
			
			//校验通过,将商品赋值后加到集合中.
			MmallOrderItem orderItem = new MmallOrderItem();
			orderItem.setUserId(userId);
			orderItem.setProductId(product.getId());
			orderItem.setProductName(product.getName());
			orderItem.setProductImage(product.getMainImage());
			orderItem.setCurrentUnitPrice(product.getPrice());
			orderItem.setQuantity(cart.getQuantity());
			orderItem.setTotalPrice(BigDecimalUtil.mult(cart.getQuantity().doubleValue(), product.getPrice().doubleValue()));
			
			orderItemList.add(orderItem);
		}
		
		return ServerResponse.createBySuccess(orderItemList);
	}

	@Override
	public ServerResponse cancelOrder(Integer userId, Long orderNo) {
		
		MmallOrder order = orderMapper.selectByUserIdOrderNo(userId, orderNo);
		if(order == null){
			return ServerResponse.createByErrorMessage("不存在该订单");
		}
		
		if(order.getStatus() != Const.OrderStatusEnum.UNPAID.getCode()){
			return ServerResponse.createByErrorMessage("已付款,无法取消订单");
		}
		
		//更新订单
		MmallOrder newOrder = new MmallOrder();
		newOrder.setId(order.getId());
		newOrder.setStatus(Const.OrderStatusEnum.CANNEL.getCode());
		
		int count = orderMapper.updateByPrimaryKeySelective(newOrder);
		if(count == 0){
			return ServerResponse.createByError();
		}
		return ServerResponse.createBySuccess();
	}

	@Override		//获取订单中的商品信息
	public ServerResponse getOrderCartProduct(Integer userId) {
		
		
		//从购物车中获取用户已勾选的商品
		List<MmallCart> cart = cartMapper.selectCartByUserId(userId);
		
		ServerResponse response = this.getCartOrderItem(userId, cart);
		
		if(!response.isSuccess()){
			return response;
		}
		
		List<MmallOrderItem> orderItemList = (List<MmallOrderItem>) response.getData();
		
		
		List<OrderItemVo> orderItemVoList = new ArrayList();
		
		BigDecimal totalPrice = new BigDecimal("0");
		for(MmallOrderItem item : orderItemList ){
			
			//算出总金额
			totalPrice = BigDecimalUtil.add(item.getTotalPrice().doubleValue(), totalPrice.doubleValue());
			
			//组装 商品详情vo.
			OrderItemVo itemVo = this.assembleOrderItemVo(item);
			orderItemVoList.add(itemVo);
		}
		
		OrderProductVo productVo = new OrderProductVo();	
		productVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
		productVo.setOrderItemVoList(orderItemVoList);
		productVo.setProductTotalPrice(totalPrice);
		
		return ServerResponse.createBySuccess(productVo);
	}

	@Override				//订单详情detail
	public ServerResponse getDetail(Integer userId, Long orderNo) {
		

		MmallOrder order = orderMapper.selectByUserIdOrderNo(userId, orderNo);
		if(order == null){
			return ServerResponse.createByErrorMessage("没有该订单");
		}
		
		List<MmallOrderItem> orderItemList = orderItemMapper.selectByUserIdOrderNo(userId, orderNo);
		
		OrderVo orderVo = this.assembleOrderVo(order, orderItemList);
		return ServerResponse.createBySuccess(orderVo);
	}

	@Override	
	public ServerResponse<PageInfo> getOrderList(Integer userId, Integer pageNum, Integer pageSize) {

		//获取订单list
		
		PageHelper.startPage(pageNum, pageSize);
		
		List<MmallOrder> orderList = orderMapper.selectByUserId(userId);
		
		List<OrderVo> orderVoList = this.assembleOrderVoList(orderList, userId);
		
		PageInfo info = new PageInfo(orderList);
		info.setList(orderVoList);
		
		return ServerResponse.createBySuccess(info);
		
	}
	
	
	//组装OrderVoList集合.
	private List<OrderVo> assembleOrderVoList(List<MmallOrder> orderList ,Integer userId ){
		
		List<OrderVo> orderVoList = new ArrayList<>();
		
		for(MmallOrder order : orderList){
			
			List<MmallOrderItem> orderItemList = new ArrayList<>();
			
			if( userId == null){
				//封装一下,管理员用户都可以查询订单列表,而管理员查询的时候不需要userid.
				orderItemList = orderItemMapper.selectByOrderNo(order.getOrderNo());
				
			}else{
				orderItemList = orderItemMapper.selectByUserIdOrderNo(userId, order.getOrderNo());
			}
			
			OrderVo ordervo = this.assembleOrderVo(order, orderItemList);
			orderVoList.add(ordervo);
		}
		
		return orderVoList;
	}
	
	
	
	// 下面是后台的功能
	
	
	@Override				//查询订单,通过订单号查询
	public ServerResponse manageGetDetail(Long orderNo) {
		
		MmallOrder order = orderMapper.selectByOrderNo(orderNo);
		if(order == null){
			return ServerResponse.createByErrorMessage("该订单不存在");
		}
		
		List<MmallOrderItem> orderItemList = orderItemMapper.selectByOrderNo(orderNo);
		
		OrderVo orderVO = this.assembleOrderVo(order, orderItemList );
		
		return ServerResponse.createBySuccess(orderVO);
	}

	@Override
	public ServerResponse<String> send_goods(Long orderNo) {
		
		MmallOrder nowOrder = new MmallOrder();
		
		MmallOrder order = orderMapper.selectByOrderNo(orderNo);
		
		if(order == null){
			return ServerResponse.createByErrorMessage("订单不存在");
		}
		
		if(order.getStatus() == Const.OrderStatusEnum.PAID.getCode()){
			//已付款,可以发货
			nowOrder.setStatus(Const.OrderStatusEnum.SHIPPED.getCode());
			nowOrder.setSendTime(new Date());
			nowOrder.setId(order.getId());
			orderMapper.updateByPrimaryKeySelective(nowOrder);
			
			return ServerResponse.createBySuccess("发货成功");
		}
		
		return ServerResponse.createByErrorMessage("发货失败");
	}

	@Override
	public ServerResponse<PageInfo> manageSearch(Long orderNo,Integer pageNum, Integer pageSize) {
		
		PageHelper.startPage(pageNum, pageSize);
		MmallOrder order = orderMapper.selectByOrderNo(orderNo);
		
		if(order == null){
			return ServerResponse.createByErrorMessage("没有找到该订单");
		}
		
		List<MmallOrderItem> orderItemList = orderItemMapper.selectByOrderNo(orderNo);
		
		OrderVo orderVo = this.assembleOrderVo(order, orderItemList);
		
		PageInfo info = new PageInfo(Lists.newArrayList(order));
		
		info.setList(Lists.newArrayList(orderVo));
		
		return ServerResponse.createBySuccess(info);
		
	}

	@Override	
	public ServerResponse manageList(Integer pageNum, Integer pageSize) {
		
		PageHelper.startPage(pageNum, pageSize);
		MmallOrderExample example = new MmallOrderExample();
		List<MmallOrder> orderList = orderMapper.selectByExample(example);
		
		List<OrderVo> orderVoList = this.assembleOrderVoList(orderList, null);
		
		PageInfo info = new PageInfo(orderList);
		info.setList(orderVoList);
		
		return ServerResponse.createBySuccess(info);
	}
	
	
	
}
